package com.example.index.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.index.mapper.HouseMapper;
import com.example.index.service.HouseService;
import com.yc.pojo.House;
import com.yc.pojo.User;
import com.yc.util.Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HouseServiceImpl extends ServiceImpl<HouseMapper, House> implements HouseService {

    @Resource
    private HouseService houseService;

    @Override
    public List<House> getHouse(String swlatitude, String swlongitude, String nelatitude, String nelongitude) {
        // 从 houseService 中获取 House 实体的信息
        List<House> houses = houseService.lambdaQuery()
                // 选择查询结果需要的字段：id, lat, lng
                .select(House::getId, House::getLat, House::getLng,House::getId,House::getIntroduce)
                // 根据纬度进行范围查询：swlatitude 和 nelatitude 是查询范围的南西和北东纬度边界值
                .between(House::getLat, swlatitude, nelatitude)
                // 并且（and）根据经度进行范围查询：swlongitude 和 nelongitude 是查询范围的南西和北东经度边界值
                .and(house -> house.between(House::getLng, swlongitude, nelongitude))
                // 执行查询并返回结果列表
                .list();
//        houses.forEach(System.out::println);
        return houses;
    }

    //发起get请求---生成openid和session_key
    public String GET(String url) {
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            //构造url对象
            URL realUrl = new URL(url);
            //获取一个对应该URL的URLConnection对象
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常出现");
        }
        //关闭资源
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("出现异常");
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> getCode(String code) {
        String requestUrl = getWX_URL(code);
        //定义json对象
        JSONObject convertvalue = new JSONObject();
        //调用get方法
        String returnvalue = GET(requestUrl);
        //解析返回值，对象解析成字符串
        convertvalue = (JSONObject) JSON.parse(returnvalue);
        Map<String, Object> map = new HashMap<>();
        String session_key = (String) convertvalue.get("session_key");
        String openID = (String) convertvalue.get("openid");
        map.put("session_key", session_key);
        map.put("openID", openID);
        return map;
    }


    public static String getWX_URL(String code) {
        //微信官方提供获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=wx66cdef4b5a650daa&secret=6196db0074075650b400635d8aa3d9b2&js_code=JSCODE&grant_type=authorization_code";
        //替换appid，appsecret，和code
        String requestUrl = WX_URL.replace("APPID", "wx66cdef4b5a650daa").//填写自己的appid
                replace("SECRET", "6196db0074075650b400635d8aa3d9b2").replace("JSCODE", code).//填写自己的appsecret，
                replace("authorization_code", "authorization_code");
        return requestUrl;
    }


    public String getAccessToken() {
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx66cdef4b5a650daa&secret=6196db0074075650b400635d8aa3d9b2";
        JSONObject convertvalue = new JSONObject();
        //调用get方法
        String returnvalue = GET(accessTokenUrl);
        //解析返回值，对象解析成字符串
        convertvalue = (JSONObject) JSON.parse(returnvalue);
        String access_token = (String) convertvalue.get("access_token");
        return access_token;
    }

    public String getPhoneNumber(String access_token,String code) {
        String getPhoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+ access_token;


//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code", code);
//
//        // 转换成JSON字符串
//        String jsonString = jsonObject.toString();
//        System.out.println(jsonString);
        System.out.println(code);
        try {
            String response = Utils.makePostRequest(getPhoneNumberUrl, code);
            System.out.println("接口返回数据：" + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

